package main

import (
	"fmt"
	"log"
	"time"
	"ebbflow/logger"
)

func main() {
	// 创建简化的日志模块
	simplifiedLogger, err := logger.NewSimplifiedEbbFlowLogger(0, "logger")
	if err != nil {
		log.Fatalf("Failed to create simplified logger: %v", err)
	}

	fmt.Println("=== EbbFlow组件延迟记录测试 ===")
	fmt.Println("记录RBC、ABA、CommonCoin、CBR、ProofChain各组件的延迟...")

	// 获取组件跟踪器
	tracker := simplifiedLogger.GetComponentTracker()

	// 模拟EbbFlow协议执行
	for epoch := 1; epoch <= 5; epoch++ {
		fmt.Printf("\n--- Epoch %d ---\n", epoch)
		
		// 模拟RBC组件延迟
		fmt.Println("执行RBC协议...")
		rbcTracker := tracker.TrackRBC(epoch*100, epoch, epoch)
		time.Sleep(50 * time.Millisecond) // 模拟RBC协议执行时间
		rbcTracker.Finish(true, "")
		fmt.Printf("RBC延迟: 50ms\n")

		// 模拟ABA组件延迟
		fmt.Println("执行ABA协议...")
		abaTracker := tracker.TrackABA(epoch*100, epoch, epoch)
		time.Sleep(80 * time.Millisecond) // 模拟ABA协议执行时间
		abaTracker.Finish(true, "")
		fmt.Printf("ABA延迟: 80ms\n")

		// 模拟CommonCoin组件延迟
		fmt.Println("执行CommonCoin协议...")
		coinTracker := tracker.TrackCommonCoin(epoch*100, epoch, epoch)
		time.Sleep(30 * time.Millisecond) // 模拟CommonCoin协议执行时间
		coinTracker.Finish(true, "")
		fmt.Printf("CommonCoin延迟: 30ms\n")

		// 模拟CBR组件延迟
		fmt.Println("执行CBR协议...")
		cbrTracker := tracker.TrackCBR(epoch*100, epoch, epoch)
		time.Sleep(60 * time.Millisecond) // 模拟CBR协议执行时间
		cbrTracker.Finish(true, "")
		fmt.Printf("CBR延迟: 60ms\n")

		// 模拟ProofChain组件延迟
		fmt.Println("执行ProofChain协议...")
		proofTracker := tracker.TrackProofChain(epoch*100, epoch, epoch)
		time.Sleep(40 * time.Millisecond) // 模拟ProofChain协议执行时间
		proofTracker.Finish(true, "")
		fmt.Printf("ProofChain延迟: 40ms\n")

		// 记录整体性能
		tps := 1000.0 + float64(epoch*100)
		latency := int64(20 + epoch*5)
		simplifiedLogger.LogPerformance(tps, latency, epoch, 1000, 250)

		// 模拟一些失败的操作
		if epoch%3 == 0 {
			fmt.Println("模拟网络故障...")
			failedTracker := tracker.TrackRBC(epoch*100, epoch, epoch)
			time.Sleep(100 * time.Millisecond)
			failedTracker.Finish(false, "Network timeout")
			fmt.Printf("RBC失败延迟: 100ms\n")
		}

		time.Sleep(1 * time.Second)
	}

	// 停止并导出
	simplifiedLogger.Stop()

	// 生成性能报告
	report := simplifiedLogger.GeneratePerformanceReport()
	fmt.Println("\n=== 组件性能分析报告 ===")
	fmt.Println(report)

	// 获取组件延迟数据
	latencies := simplifiedLogger.GetComponentLatencies()
	fmt.Println("\n=== 详细组件延迟数据 ===")
	for component, componentLatencies := range latencies {
		fmt.Printf("\n【%s】\n", component)
		for i, latency := range componentLatencies {
			fmt.Printf("  操作%d: 延迟=%dms, 成功=%t, 实例=%d\n", 
				i+1, latency.Duration, latency.Success, latency.InstanceID)
		}
	}

	fmt.Println("\n测试完成！组件延迟数据已保存到 logger/ 目录")
}
